package com.luo.d3s.light.mybatis.ec.domain.base;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.luo.d3s.core.domain.adpator.light.CrudRepositoryLight;

import java.util.Collection;
import java.util.Objects;

/**
 * 基础仓库接口 - 实现CurdRepositoryLight<br/>
 * 注：兼容CrudRepository接口，即便后续有需要切换到完整DDD架构，也不需要修改调用处代码
 *
 * @author luohq
 * @date 2023-07-04 10:37
 * @see com.luo.d3s.core.domain.adpator.CrudRepository
 */
public interface BaseRepository<T extends BaseEntity> extends CrudRepositoryLight<T, Long>, BaseMapper<T> {
    /**
     * save aggregateRoot
     *
     * @param aggregateRoot aggregateRoot
     * @return aggregateRoot
     */
    @Override
    default T save(T aggregateRoot) {
        //ID已存在，则修改
        if (Objects.nonNull(aggregateRoot.getId()) && this.exists(aggregateRoot.getId())) {
            this.updateById(aggregateRoot);
        } else {
            //ID不存在，则新增
            this.insert(aggregateRoot);
        }
        //返回分类实体信息
        return aggregateRoot;
    }

    /**
     * find aggregateRoot by id
     *
     * @param id id
     * @return aggregateRoot
     */
    @Override
    default T findById(Long id) {
        return this.selectById(id);
    }

    /**
     * remove aggregateRoot by id
     *
     * @param id id
     * @return remove count
     */
    @Override
    default Integer removeById(Long id) {
        return this.deleteById(id);
    }

    /**
     * 聚合根ID是否存在
     *
     * @param id 聚合根ID
     * @return 是否存在
     */
    default Boolean exists(Long id) {
        return this.exists(Wrappers.<T>query().eq("id", id));
    }

    /**
     * batch remove aggregateRoot by ids
     *
     * @param ids ids
     * @return remove count
     */
    default Integer removeByIds(Collection<Long> ids) {
        return this.deleteBatchIds(ids);
    }
}
